package org.example.web;

import lombok.extern.slf4j.Slf4j;
import org.example.bean.ExamSubmission;
import org.example.bean.Result;
import org.example.dto.ExamsDTo;
import org.example.dto.StudentInfoDTO;
import org.example.feign.ExamService;
import org.example.feign.StudenService;
import org.example.service.ExamSubmissionService;
import org.example.service.StudentHeartbeatService;
import org.example.service.StudentService;
import org.example.util.HeartbeatScheduler;
import org.example.util.IpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;



@RestController
@RequestMapping("/api")
@Slf4j
public class ExamController {
    @Autowired
    private ExamService examService; //远程调用
    @Autowired
    private StudentService studentService;
    @Autowired  // 添加注入
    private StudenService studenService;
    private String localIpAddress;
//    @Autowired
//    private HeartbeatScheduler heartbeatScheduler;

    @Autowired
    ExamSubmissionService examSubmissionService;
    @Autowired
    private StudentHeartbeatService heartbeatService;     //WebSocket

    public ExamController() {
        this.localIpAddress = IpUtil.getLocalIpAddress();
        System.out.println("本机IP地址：" + localIpAddress);
    }


    /**
     * 连接教师机
     * @return 连接结果
     */
    @PostMapping("/connect")
    public String connect() {
        return heartbeatService.connect() ?
                "成功连接到教师机" : "连接教师机失败";
    }

    /**
     * 断开与教师机的连接
     * @return 断开结果
     */
    @PostMapping("/disconnect")
    public String disconnect() {
        heartbeatService.disconnect();
        return "已断开与教师机的连接";
    }
    /**
     * 校验登陆信息
     *
     * @return
     */
    @CrossOrigin("*")
    @PostMapping("/add")
    public Result add(@RequestBody ExamSubmission examSubmission) {
        try {
            if (examSubmission == null || examSubmission.getExamNumber() == null) {
                return Result.error("参数不能为空");
            }

            // 使用MyBatis-Plus的save方法
            boolean success = examSubmissionService.save(examSubmission);

            if (success) {
              //   插入成功后通知教师机
                notifyTeacherMachine(examSubmission.getExamNumber(),
                        examSubmission.getStudentName(),
                        examSubmission.getMachineId());
                return Result.success("添加成功");
            } else {
                return Result.error("添加失败：数据库操作未成功");
            }
        } catch (Exception e) {
            log.error("添加考试提交记录失败", e);
            return Result.error("添加失败：" + e.getMessage());
        }
    }


    /**
     * 调用老师模块，查询考试列表
     *
     * @return
     */
    @PostMapping("/list")
    @CrossOrigin("*")
    public ExamsDTo queryData(@RequestBody ExamsDTo exams) {
        ExamsDTo examsDTo = new ExamsDTo();
        examsDTo.setSchoolId( exams.getSchoolId());
        ExamsDTo select = examService.select(examsDTo);
        return select;
    }


    /**
     * 通知教师机考生登录信息
     */
    private void notifyTeacherMachine(String examNumber, String studentName, Integer machineId) {
        try {
            StudentInfoDTO request = StudentInfoDTO.builder()
                    .examNumber(examNumber)
                    .name(studentName)
                    .ip(localIpAddress)
                    .machineId(machineId)
                    .ok("ping")
                    .build();
            // 调用Feign客户端通知教师机
            StudentInfoDTO response = studenService.select(request);
            System.out.println("教师机通知结果: " + response);
            // 动态启动定时器
            heartbeatService.connect();
           // heartbeatScheduler.startHeartbeat();
        } catch (Exception e) {
            System.err.println("通知教师机失败: " + e.getMessage());
        }
    }
}


